<?php

namespace think\seecms\middleware;

use Closure;
use seecms\lib\Auth;
use magein\utils\Result;
use think\Request;

/**
 * 验证权限
 */
class PermissionMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $path_info = $request->pathinfo() ?: $request->baseUrl();
        if (!Auth::user()->checkPathPermission($path_info)) {
            $url = preg_replace('/^admin/', 'admin', $path_info);
            $url = trim($url, '/');
            if ($request->isAjax()) {
                return json(Result::error('No access permission', 3003, ['url' => $url])->toArray());
            } else {
                return redirect(auth_route('user/noPermission?url=' . $url));
            }
        }
        return $next($request);
    }
}